package com.alvin.springshiro.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;

import java.util.Optional;

@Log4j2
public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    public static ChannelGroup channelGroup;
    static {
        channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    }
    //客户端与服务器建立连接的时候触发，
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加到channelGroup通道组
        channelGroup.add(ctx.channel());
        log.info("与客户端建立连接，通道开启！Channel id : " + ctx.channel().id());
        ctx.channel().writeAndFlush("与客户端建立连接，通道开启！Channel id : " + ctx.channel().id());
    }
    //客户端与服务器关闭连接的时候触发，
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端断开连接，通道关闭！Channel id : " + ctx.channel().id());
        channelGroup.remove(ctx.channel());
        sendAllMessage("与客户端断开连接，通道关闭！Channel id : " + ctx.channel().id());
    }
    //服务器接受客户端的数据信息，
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg){
        log.info("服务器收到Channel("+ctx.channel().id()+")数据：" + msg.text());

        //解析发送的报文
        JSONObject jsonObject = JSON.parseObject(msg.text());
        //追加发送人(防止串改)
        jsonObject.put("from_user_id",ctx.channel().id());
        String toUserId = jsonObject.getString("to_user_id");
        String message = jsonObject.getString("msg");


        if(StringUtils.isNotBlank(toUserId)){
            Optional<Channel> optionalChannel = channelGroup.stream().filter(channel -> channel.id().toString().equals(toUserId)).findFirst();

            Channel toChannel = null;

            if(optionalChannel.isPresent()){
                toChannel = optionalChannel.get();
            }

            if(toChannel!=null){
                sendMessage(toChannel, "Channel("+ ctx.channel().id() +")向（" + toChannel.id()+")发送消息：" + message);
            }else{
                sendMessage(ctx.channel(), "找不到id为（"+ toUserId +")的channel，消息发送失败。");
            }

        }else{
            sendAllMessage("服务器收到Channel("+ctx.channel().id()+")数据：" + message);
        }

    }
    //给固定的人发消息
    private void sendMessage(Channel toChannel, String msg) {
        toChannel.writeAndFlush(new TextWebSocketFrame(msg));
    }
    //发送群消息,此时其他客户端也能收到群消息
    private void sendAllMessage(String message){
        channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    }
}